package com.authorization.project.authorization.controller;

import com.authorization.common.utils.CreateLic;
import com.authorization.common.utils.FileUtil;
import com.authorization.common.utils.poi.ExcelUtil;
import com.authorization.framework.aspectj.lang.annotation.Log;
import com.authorization.framework.aspectj.lang.enums.BusinessType;
import com.authorization.framework.web.controller.BaseController;
import com.authorization.framework.web.domain.AjaxResult;
import com.authorization.framework.web.page.TableDataInfo;
import com.authorization.project.authorization.domain.Authorization;
import com.authorization.project.authorization.domain.AuthorizationHistory;
import com.authorization.project.authorization.service.*;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Objects;

/**
 * 授权注册信息Controller
 * 
 * @author 李晓雷
 * @date 2020-04-26
 */
@RestController
@RequestMapping("/authorization/authorization")
public class AuthorizationController extends BaseController
{
    @Autowired
    private IAuthorizationService authorizationService;

    @Autowired
    private IAuthorizationHistoryService iAuthorizationHistoryService;

    @Autowired
    private IAuthorizationTokenService authorizationTokenService;

    @Autowired
    private IModuleService iModuleService;

    @Autowired
    private IProductService iProductService;


    /**
     * 查询授权注册信息列表
     */
    @PreAuthorize("@ss.hasPermi('authorization:authorization:list')")
    @GetMapping("/list")
    public TableDataInfo list(Authorization authorization)
    {
        startPage();
        if(Objects.equals(authorization.getStatus(), "2")){
            authorization.setStatus(null);
            authorization.setOldAndAuditStatus("1");
        }
        List<Authorization> list = authorizationService.selectAuthorizationList(authorization);
        return getDataTable(list);
    }

    /**
     * 导出授权注册信息列表
     */
    @PreAuthorize("@ss.hasPermi('authorization:authorization:export')")
    @Log(title = "授权注册信息", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Authorization authorization)
    {
        List<Authorization> list = authorizationService.selectAuthorizationList(authorization);
        ExcelUtil<Authorization> util = new ExcelUtil<Authorization>(Authorization.class);
        return util.exportExcel(list, "authorization");
    }

    /**
     * 获取授权注册信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('authorization:authorization:query')")
    @GetMapping(value = "/{userid}")
    public AjaxResult getInfo(@PathVariable("userid") String userid)
    {
        return AjaxResult.success(authorizationService.selectAuthorizationById(userid));
    }

    /**
     * 新增授权注册信息
     */
    @PreAuthorize("@ss.hasPermi('authorization:authorization:add')")
    @Log(title = "授权注册信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Authorization authorization)
    {
        authorization.setUserid(authorization.getUserNumber());
        return toAjax(authorizationService.insertAuthorization(authorization));
    }

    /**
     * 修改授权注册信息
     */
    @PreAuthorize("@ss.hasPermi('authorization:authorization:edit')")
    @Log(title = "授权注册信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Authorization authorization)
    {
        authorization.setUserid(authorization.getUserNumber());
        return toAjax(authorizationService.updateAuthorization(authorization));
    }

    /**
     * 删除授权注册信息
     */
    @PreAuthorize("@ss.hasPermi('authorization:authorization:remove')")
    @Log(title = "授权注册信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userids}")
    public AjaxResult remove(@PathVariable String[] userids)
    {
        return toAjax(authorizationService.deleteAuthorizationByIds(userids));
    }

    /**
     * 根据客户编号修改状态
     */
    @PostMapping(value = "/updateAuthorizationState")
    public AjaxResult updateAuthorizationState(@RequestBody Authorization authorization)
    {
        return toAjax(authorizationService.updateAuthorizationState(authorization.getUserid(), authorization.getStatus()));
    }

    /**
     * 获取授权注册信息详细信息
     */
    @GetMapping(value = "authorizationHistory/{userid}")
    public AjaxResult authorizationHistory(@PathVariable("userid") String userid)
    {
        AuthorizationHistory authorizationHistory = new AuthorizationHistory();
        authorizationHistory.setUrls(userid);
        return AjaxResult.success(iAuthorizationHistoryService.selectAuthorizationHistoryList(authorizationHistory));
    }

    /**
     * 对外开放添加接口
     * @param authorization
     * @return
     */
    @PostMapping(value = "/api/save")
    public AjaxResult apiInsertAuthorization(@RequestBody Authorization authorization)
    {
        int status = authorizationTokenService.verifyToken(authorization.getToken());
        if(status == 0){
            return AjaxResult.error("token失效");
        }
        authorization.setAdduser(authorizationTokenService.selectUserNameByToken(authorization.getToken()));
        authorization.setUserid(authorization.getUserNumber());
        authorization.setSecretversion("v5");
        authorization.setProductId(iProductService.selectIdByName(authorization.getProductName()));
        return toAjax(authorizationService.apiInsertAuthorization(authorization));
    }

    /**
     * 根据客户编号,机器码,token 查询审核状态
     * @param token
     * @return
     */
    @GetMapping(value = "/api/selstatus")
    public AjaxResult apiSelstatus(String userid,  String token)
    {
        int status = authorizationTokenService.verifyToken(token);
        if(status == 0){
            return AjaxResult.error("token失效");
        }
        return AjaxResult.success(authorizationService.apiSelstatus(userid));
    }

    /**
     * lic 文件下载
     */
    @GetMapping("/api/licdown")
    @ResponseBody
    public AjaxResult  licdown(HttpServletResponse response, String userid,  String token)
            throws IOException {
        int status = authorizationTokenService.verifyToken(token);
        if(status == 0){
            return AjaxResult.error("token失效");
        }
        licdownLic(response,userid);
        return AjaxResult.success("下载成功");
    }

    /**
     * lic 文件下载
     */
    @GetMapping("/licdown")
    @ResponseBody
    public void licdown(HttpServletResponse response, String userid)
            throws IOException {
        licdownLic(response,userid);
    }

    private void licdownLic(HttpServletResponse response, String userid) {
        JSONObject json = new JSONObject();
        Authorization authorizationMap = authorizationService.selectAuthorizationById(userid);
        if (authorizationMap != null) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String begiDate = sdf.format(authorizationMap.getBegidate());
            String endDate = sdf.format(authorizationMap.getEnddate());
            json = new JSONObject();
            json.put("userid", userid);
            json.put("isSecret", authorizationMap.getIssecret());
            json.put("mainVersion", authorizationMap.getMainversion());
            json.put("secretVersion", authorizationMap.getSecretversion());
            json.put("username", authorizationMap.getUsername());
            json.put("services", authorizationMap.getServices());
            json.put("begiDate", begiDate);
            json.put("endDate", endDate);
            json.put("contacts", authorizationMap.getContacts());
            json.put("behavior", authorizationMap.getBehavior());
            json.put("urls", authorizationMap.getUrls());
            json.put("machineCode", authorizationMap.getMachineCode());
            json.put("config", authorizationMap.getConfig());
            json.put("status", authorizationMap.getStatus());
            json.put("productId", authorizationMap.getProductId());
            // 添加模块英文名称
            json.put("moduleEnglish", iModuleService.selectEnglishListByUserId(userid));

            String userpath = json.get("userid") == null ? "so-2018-4" : json.get("userid").toString();
            String path = System.getProperty("user.dir") + "/licbin/" + userpath + "/so.lic";
            System.out.println("创建" + path);
            File file = new File(path);
            if(file.exists()){
                file.delete();
            }
            String fileName = "";
            if(Objects.equals("v5",  authorizationMap.getMainversion())){
                path = CreateLic.createLicFileV5(json);
                fileName = "v5so.zip";
            }else {
                path = CreateLic.createLicFile(json);
                fileName = userid + "-so.lic";
            }
            if (!"".equals(path)) {
                download(path, fileName, response);
                //删除文件
                FileUtil.delFile(System.getProperty("user.dir") + "/licbin/" + userpath);
                FileUtil.delFile(System.getProperty("user.dir") + "/v5lic/" + userpath);
                FileUtil.delFile(System.getProperty("user.dir") + "/lic/" + userpath);
            }

        }
    }


    public HttpServletResponse download(String path, String name, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            //String filename = file.getName();
            String filename = name;
            // 取得文件的后缀名。

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }

}
